package org.ubc.cs410.disposal2020.server;

import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ubc.cs410.disposal2020.Game;
import org.ubc.cs410.disposal2020.Map;
import org.ubc.cs410.disposal2020.PMF;
import org.ubc.cs410.disposal2020.Player;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

/*
 * Servlet for generating start.html
 */

public class GameStartServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {

		// Template data
		java.util.Map<String, Object> root = new HashMap<String, Object>();

		// Page title
		root.put("title", "Start a New Game");

		// Get a list of the maps
		java.util.Map<String, String> mapsMap = new HashMap<String, String>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Map.class);
			List<Map> maps = (List<Map>) query.execute();
			for (Map m : maps) {
				mapsMap.put(m.getId().toString(), m.getName());
			}
		} finally {
			pm.close();
		}
		root.put("maps", mapsMap);

		// Do the rendering
		ServletUtils.renderTemplate(getServletContext(), root, "Start.ftl",
				resp, req.getRequestURI());
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String mapId = "";
		try {
			mapId = req.getParameter("map");
		} catch (Exception e) {
			e.printStackTrace();
		}
		String g = "";
		try {
			g = req.getParameter("garbage");
		} catch (Exception e) {
			e.printStackTrace();
		}
		int garbage;
		try {
			garbage = Integer.parseInt(g);
		} catch (NumberFormatException nfe) {
			garbage = 0;
		}

		PersistenceManager pm = PMF.get().getPersistenceManager();
		// Getting the map from datastore
		Key k = KeyFactory.createKey(Map.class.getSimpleName(), new Integer(
				mapId).longValue());
		Map map = pm.getObjectById(Map.class, k);

		Game game = null;
		if (garbage == 0) {
			game = new Game(map, new ArrayList<Player>());
		} else {
			game = new Game(map, new ArrayList<Player>(), garbage);
		}

		Player player = new Player(UserServiceFactory.getUserService().getCurrentUser().getEmail(), game);
		game.addPlayer(player);

		pm.makePersistent(game);

		resp.sendRedirect(resp.encodeRedirectURL("/waiting.html"));
		//resp.sendRedirect(resp.encodeRedirectURL("/game/"+game.getSlug()));
	}
}
